/**
 * 性能监控与优化工具
 */

// 性能数据收集
let performanceData = {
  routeChanges: [],
  componentRenders: {},
  memoryUsage: [],
  longTasks: []
}

// 清理大型数据结构，避免内存泄漏
const cleanupPerformanceData = () => {
  // 保留最近100条路由变化记录
  if (performanceData.routeChanges.length > 100) {
    performanceData.routeChanges = performanceData.routeChanges.slice(-100)
  }
  
  // 保留最近100条内存使用记录
  if (performanceData.memoryUsage.length > 100) {
    performanceData.memoryUsage = performanceData.memoryUsage.slice(-100)
  }
  
  // 保留最近100条长任务记录
  if (performanceData.longTasks.length > 100) {
    performanceData.longTasks = performanceData.longTasks.slice(-100)
  }
  
  // 组件渲染数据清理
  Object.keys(performanceData.componentRenders).forEach(key => {
    const renderData = performanceData.componentRenders[key]
    if (renderData.history && renderData.history.length > 50) {
      performanceData.componentRenders[key].history = renderData.history.slice(-50)
    }
  })
}

// 定期清理
setInterval(cleanupPerformanceData, 60000) // 每分钟清理一次

// 监控路由变化性能
export const monitorRouteChange = (from, to, duration) => {
  performanceData.routeChanges.push({
    from: from.path,
    to: to.path,
    duration,
    timestamp: Date.now()
  })
  
  // 如果路由变化时间过长，记录警告
  if (duration > 500) {
    console.warn(`路由切换耗时过长: ${from.path} -> ${to.path}, 耗时 ${duration}ms`)
  }
}

// 监控内存使用情况
export const monitorMemory = () => {
  if (performance && performance.memory) {
    performanceData.memoryUsage.push({
      used: performance.memory.usedJSHeapSize,
      total: performance.memory.totalJSHeapSize,
      limit: performance.memory.jsHeapSizeLimit,
      timestamp: Date.now()
    })
    
    // 如果内存使用超过80%，发出警告
    const memoryUsage = performance.memory.usedJSHeapSize / performance.memory.jsHeapSizeLimit
    if (memoryUsage > 0.8) {
      console.warn(`内存使用率过高: ${Math.round(memoryUsage * 100)}%`)
    }
  }
}

// 开始定期监控内存
if (typeof window !== 'undefined') {
  setInterval(monitorMemory, 10000) // 每10秒检查一次
}

// 监控长任务
export const setupLongTaskMonitoring = () => {
  if (typeof window !== 'undefined' && 'PerformanceObserver' in window) {
    try {
      const observer = new PerformanceObserver((list) => {
        for (const entry of list.getEntries()) {
          // 记录超过100ms的任务
          performanceData.longTasks.push({
            duration: entry.duration,
            startTime: entry.startTime,
            timestamp: Date.now()
          })
          
          if (entry.duration > 200) {
            console.warn(`检测到长任务: ${Math.round(entry.duration)}ms`)
          }
        }
      })
      
      observer.observe({ entryTypes: ['longtask'] })
    } catch (e) {
      console.error('不支持长任务监控:', e)
    }
  }
}

// 组件渲染性能监控
export const monitorComponentRender = (componentName, renderTime) => {
  if (!performanceData.componentRenders[componentName]) {
    performanceData.componentRenders[componentName] = {
      count: 0,
      totalTime: 0,
      maxTime: 0,
      history: []
    }
  }
  
  const compData = performanceData.componentRenders[componentName]
  compData.count++
  compData.totalTime += renderTime
  compData.maxTime = Math.max(compData.maxTime, renderTime)
  compData.history.push({
    time: renderTime,
    timestamp: Date.now()
  })
  
  // 如果渲染时间过长，记录警告
  if (renderTime > 50) {
    console.warn(`组件 ${componentName} 渲染时间过长: ${renderTime}ms`)
  }
}

// 优化函数：防抖
export const debounce = (fn, delay) => {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 优化函数：节流
export const throttle = (fn, delay) => {
  let last = 0
  return function(...args) {
    const now = Date.now()
    if (now - last > delay) {
      last = now
      fn.apply(this, args)
    }
  }
}

// 优化DOM操作
export const batchDOMUpdates = (updates) => {
  return new Promise(resolve => {
    // 使用requestAnimationFrame进行批量DOM更新
    requestAnimationFrame(() => {
      updates()
      resolve()
    })
  })
}

// 检查并优化大型列表渲染
export const optimizeListRendering = (listId, items, renderItem, options = {}) => {
  const container = document.getElementById(listId)
  if (!container) return
  
  const {
    itemHeight = 30,
    bufferSize = 5,
    batchSize = 20,
    key = item => item.id
  } = options
  
  const totalHeight = items.length * itemHeight
  
  // 设置容器高度
  container.style.height = `${totalHeight}px`
  container.style.position = 'relative'
  container.style.overflow = 'auto'
  
  // 优化滚动处理
  const handleScroll = throttle(() => {
    const scrollTop = container.scrollTop
    const containerHeight = container.clientHeight
    
    // 计算可视范围内的项
    const startIndex = Math.floor(scrollTop / itemHeight) - bufferSize
    const endIndex = Math.ceil((scrollTop + containerHeight) / itemHeight) + bufferSize
    
    // 确保索引在有效范围内
    const validStartIndex = Math.max(0, startIndex)
    const validEndIndex = Math.min(items.length - 1, endIndex)
    
    // 清空容器
    container.innerHTML = ''
    
    // 分批次添加DOM元素以避免长任务
    const renderBatch = (start, end) => {
      if (start > end) return
      
      const fragment = document.createDocumentFragment()
      
      for (let i = start; i <= Math.min(end, validEndIndex); i++) {
        const item = items[i]
        const itemElement = renderItem(item)
        
        if (itemElement) {
          // 设置绝对定位
          itemElement.style.position = 'absolute'
          itemElement.style.top = `${i * itemHeight}px`
          itemElement.style.width = '100%'
          itemElement.style.height = `${itemHeight}px`
          
          // 设置数据属性用于识别
          itemElement.dataset.index = i
          itemElement.dataset.key = key(item)
          
          fragment.appendChild(itemElement)
        }
      }
      
      container.appendChild(fragment)
      
      // 如果还有项未渲染，继续下一批次
      if (end < validEndIndex) {
        setTimeout(() => {
          renderBatch(end + 1, end + batchSize)
        }, 0)
      }
    }
    
    // 开始渲染第一批
    renderBatch(validStartIndex, validStartIndex + batchSize - 1)
  }, 100)
  
  // 添加滚动事件监听
  container.addEventListener('scroll', handleScroll)
  
  // 初始渲染
  handleScroll()
  
  // 返回清理函数
  return () => {
    container.removeEventListener('scroll', handleScroll)
  }
}

// 获取性能报告
export const getPerformanceReport = () => {
  const now = Date.now()
  const last10Minutes = now - 600000 // 最近10分钟
  
  // 分析路由变化
  const recentRouteChanges = performanceData.routeChanges.filter(
    item => item.timestamp > last10Minutes
  )
  
  const avgRouteChangeDuration = recentRouteChanges.length > 0
    ? recentRouteChanges.reduce((sum, item) => sum + item.duration, 0) / recentRouteChanges.length
    : 0
  
  // 分析长任务
  const recentLongTasks = performanceData.longTasks.filter(
    item => item.timestamp > last10Minutes
  )
  
  const longTasksCount = recentLongTasks.length
  const avgLongTaskDuration = longTasksCount > 0
    ? recentLongTasks.reduce((sum, item) => sum + item.duration, 0) / longTasksCount
    : 0
  
  // 识别慢组件
  const slowComponents = []
  Object.entries(performanceData.componentRenders).forEach(([name, data]) => {
    if (data.count > 0 && data.totalTime / data.count > 20) {
      slowComponents.push({
        name,
        avgRenderTime: data.totalTime / data.count,
        renderCount: data.count,
        maxRenderTime: data.maxTime
      })
    }
  })
  
  // 按平均渲染时间降序排列
  slowComponents.sort((a, b) => b.avgRenderTime - a.avgRenderTime)
  
  return {
    timestamp: now,
    routeChanges: {
      count: recentRouteChanges.length,
      avgDuration: avgRouteChangeDuration
    },
    longTasks: {
      count: longTasksCount,
      avgDuration: avgLongTaskDuration
    },
    slowComponents: slowComponents.slice(0, 10), // 只返回最慢的10个组件
    memoryUsage: performanceData.memoryUsage.length > 0
      ? performanceData.memoryUsage[performanceData.memoryUsage.length - 1]
      : null
  }
}

// 初始化性能监控
export const initPerformanceMonitoring = () => {
  if (typeof window !== 'undefined') {
    // 设置长任务监控
    setupLongTaskMonitoring()
    
    // 首次内存检查
    monitorMemory()
    
    // 输出初始化信息
    console.log('性能监控已初始化')
  }
}

export default {
  initPerformanceMonitoring,
  monitorRouteChange,
  monitorComponentRender,
  getPerformanceReport,
  debounce,
  throttle,
  batchDOMUpdates,
  optimizeListRendering
} 